package com.swak.persistence.mybatis.methods.impls;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.AbstractMethod;
import com.swak.persistence.mybatis.methods.Sqls;
import com.swak.utils.StringUtils;

/**
 * 有选择性的更新相关值，不能将某个值设置为 NULL.
 * 
 * @ClearSelective 清除选择的列，将选择的列设置为 NULL.
 * @author DELL
 */
public class UpdateSelective extends AbstractMethod {

	@Override
	protected void doInject() {
		if (!this.supportMethod(Sqls.UPDATE_SELECTIVE)) {
			return;
		}

		String sql = new StringBuilder().append(SCRIPT_START).append(UPDATE).append(SPACE).append(this.table.getName())
				.append(SPACE).append(this.convertSet(this.parseUpdateProperty())).append(SPACE)
				.append(this.parseWhereLogicDelEqualColumn(false)).append(this.parsePkEqualColumns()).append(SPACE)
				.append(this.parseOptimismLockCheckColumn()).append(SCRIPT_END).toString();

		this.addUpdateMappedStatement(this.table.entity, Sqls.UPDATE_SELECTIVE.getMethod(), sql);
	}

	protected String convertSet(String sql) {
		return SET_START + sql + SET_END;
	}

	protected String parseOptimismLockCheckColumn() {
		if (this.table.define.useOptimismLock()) {
			return OP_LOCK_CHECK;
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 解析修改列
	 */
	protected String parseUpdateProperty() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : this.table.columns) {
			if (!column.isPk() && !column.isCreateDate() && !column.isVersion()) {
				sql.append("<if test=\"").append(column.javaProperty).append(" != null\">").append(column.name)
						.append(EQUALS).append(HASH_LEFT_BRACE).append(column.javaPropertyEl).append(RIGHT_BRACE)
						.append(SPLIT).append("</if>");
			}
		}
		if (this.table.define.useOptimismLock()) {
			sql.append(OP_LOCK_ADD);
		}
		return sql.toString();
	}
}